package cn.edu.scnu.lastandroid.ui.place

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.content.ContextCompat.startActivity
import androidx.drawerlayout.widget.DrawerLayout
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import cn.edu.scnu.lastandroid.R
import cn.edu.scnu.lastandroid.logic.model.Place
import cn.edu.scnu.lastandroid.ui.weather.WeatherActivity
import kotlin.random.Random

class PlaceAdapter(private val fragment: Fragment, private  val placeList: List<Place>):
    RecyclerView.Adapter<PlaceAdapter.ViewHolder>(){
    inner class ViewHolder(view: View): RecyclerView.ViewHolder(view) {
        val placeName : TextView = view.findViewById(R.id.placeName)
        val placeAddress : TextView = view.findViewById(R.id.placeAddress)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.place_item, parent, false)
        /*这个函数是fozu代为写的，目前属于15.6的标红部分已写完，剩余标红部分是15.5部分*/
        val holder = ViewHolder(view)
        holder.itemView.setOnClickListener{
            val position=holder.adapterPosition
            val place = placeList[position]
            val activity = fragment.activity
            if(activity is WeatherActivity) {
                val drawerLayout : DrawerLayout?  = fragment.view?.findViewById(R.id.drawerLayout)
                drawerLayout?.closeDrawers()
                Log.d("location_lng", place.lng)
                activity.viewModel.lngStr = place.lng
                activity.viewModel.latStr = place.lat
                activity.viewModel.cityStr = place.name
                activity.refreshWeather()
            }else{
                val intent = Intent(parent.context, WeatherActivity::class.java).
                apply{
                    putExtra("location_lng",place.lng)
                    putExtra("location_lat",place.lat)
                    putExtra("place_name",place.name)
                }
                Log.d("location_lng", place.lng)
                fragment.startActivity(intent)
                activity?.finish()
            }
            (fragment as PlaceFragment).viewModel.savePlace(place)
        }
        return holder
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val place = placeList[position]
        holder.placeName.text = place.name
        holder.placeAddress.text = place.country + place.adm1 + place.adm2
    }

    override fun getItemCount() = placeList.size
}